package com.scau.phradmin.business.doctor.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scau.phradmin.common.exceptions.ErrorCode;
import com.scau.phradmin.common.util.Md5Encipher;
import com.scau.phradmin.common.util.PageDTO;
import com.scau.phradmin.common.util.StrTool;
import com.scau.phradmin.domain.entity.Doctor;
import com.scau.phradmin.domain.mapper.DoctorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class DoctorService {
    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private Md5Encipher md5Encipher;
    /**
     * 查询所有用户信息
     * @param pages
     * @return
     */
    public Object selectAll(int pages){
        Page page=null;
        if(pages>0) {
            page=new Page(pages,10);
        }
        else{
            page=new Page(1,10);
        }
        List<Doctor> list=doctorMapper.queryAll(page);
        return PageDTO.valueOf(list,page);
    }
    /**
     * 通过id查询唯一用户信息
     * @param telephone
     * @return
     */
    public Object selectByTelephone(String telephone){
        StrTool.sql_inj(telephone);
        return doctorMapper.queryOne(telephone);
    }

    /**
     * 通过主键修改唯一用户信息，成功返回true，否则返回false
     * @param doctor
     * @return
     */

    @Transactional
    public boolean edit(Doctor doctor){
        return doctorMapper.updateById(doctor)>0;
    }

    /**
     * 添加用户
     * @param doctor
     * @return
     */
    @Transactional
    public boolean add(Doctor doctor){
        doctor.setPassword(md5Encipher.encrypt(doctor.getPassword()));
        doctor.setRegisteredDate(LocalDate.now());
        return doctorMapper.insert(doctor) > 0;
    }

    /**
     * 通过id删除唯一用户
     * @param id
     * @return
     */
    @Transactional
    public boolean delete(Long id){
        return doctorMapper.deleteById(id) > 0;
    }

    public Object register(Doctor doctor)
    {
        if(doctorMapper.queryByTelephone(doctor.getTelephone())==0 &&add(doctor))
            return ErrorCode.SUCCESS;
        else return ErrorCode.AUTH_USER_EXIST;
    }

    public Object login(String telephone,String passWord)
    {
        StrTool.sql_inj(telephone);
        Doctor doctor=doctorMapper.queryOne(telephone);
        if(doctor==null)
            return ErrorCode.USER_NOT_REGISTER;
        else if(!md5Encipher.encrypt(passWord).equals(doctor.getPassword()))
            return  ErrorCode.AUTH_ERROR;
        else return ErrorCode.SUCCESS;
    }
}
